<template>
  <view class="mall-container">
    <!-- 搜索框 -->
    <view class="search-box">
      <view class="search-bar">
        <text class="label">产品</text>
        <input 
          type="text" 
          v-model="keyword"
          clearable
          placeholder="请输入商品名称" 
          placeholder-class="placeholder"
          @confirm="handleSearch"
        />
        <view class="search-icon"></view>
      </view>
    </view>

    <!-- 标签栏 -->
    <scroll-view class="tag-list" scroll-x>
      <view 
        class="tag-item" 
        v-for="item in typeList" 
        :key="item.id"
        :class="{ active: currentType === item.id }"
        @tap="handleTypeChange(item.id)"
      >
        {{ item.typeName }}
      </view>
    </scroll-view>

    <!-- 商品列表 -->
    <scroll-view 
      class="product-list" 
      scroll-y
      refresher-enabled
      enhanced
      :show-scrollbar="false"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <view 
        class="product-item" 
        v-for="item in productList" 
        :key="item.id" 
        @tap="handleProductClick(item)"
      >
        <image class="product-image" :src="BASE_URL + item.headerImg || DEFAULT_IMAGE" mode="aspectFill" />
        <view class="product-info">
          <text class="product-name">{{ item.name }}</text>
          <view class="project-info">
            <text class="label">项目编号</text>
            <text class="value">{{ item.id }}</text>
          </view>
          <view class="project-info">
            <text class="label">项目规格</text>
            <text class="value">{{ item.omsGoodsSkus?.map(sku => `${sku.skuName}*1`).join('、') || '-' }}</text>
          </view>
          <view class="price-info">
            <view class="price">
              <text class="symbol">¥</text>
              <text class="amount">{{ item.price }}</text>
            </view>
            <text class="original-price" v-if="item.originalPrice">¥{{ item.originalPrice }}</text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="loading" v-if="isLoading">加载中...</view>
      <view class="no-more" v-if="noMore">没有更多了</view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { DEFAULT_IMAGE } from "@/config/images";
import { getGoodsTypeList, getGoodsList } from '@/api/goods';
import type { GoodsListParams } from '@/api/goods';
import { BASE_URL, IMG_URL } from '@/utils/request';

// 搜索关键词
const keyword = ref('');

// 商品类型列表
const typeList = ref<any[]>([]);
const currentType = ref<number>();

// 商品列表
const productList = ref<any[]>([]);
const page = ref(1);
const pageSize = 10;
const isLoading = ref(false);
const noMore = ref(false);
const isRefreshing = ref(false);

// 获取商品类型列表
const fetchTypeList = async () => {
  try {
    const res = await getGoodsTypeList();
    typeList.value = res.rows;
    if (res.rows.length > 0) {
      currentType.value = res.rows[0].id;
      fetchGoodsList(true);
    }
  } catch (error) {
    console.error('获取商品类型列表失败:', error);
    uni.showToast({
      title: '获取商品类型列表失败',
      icon: 'none'
    });
  }
};

// 获取商品列表
const fetchGoodsList = async (replace: boolean = false) => {
  if (isLoading.value) return;
  isLoading.value = true;
  
  try {
    const params: GoodsListParams = {
      typeId: currentType.value,
      name: keyword.value || '',
      pageNum: page.value,
      pageSize
    };
    
    const res = await getGoodsList(params);
    const list = res.rows || [];
    
    if (replace) {
      productList.value = list;
    } else {
      productList.value.push(...list);
    }
    
    noMore.value = list.length < pageSize;
    if (!noMore.value) {
      page.value++;
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    uni.showToast({
      title: '获取商品列表失败',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
    isRefreshing.value = false;
  }
};

// 切换商品类型
const handleTypeChange = (typeId: number) => {
  if (currentType.value === typeId) return;
  currentType.value = typeId;
  page.value = 1;
  noMore.value = false;
  fetchGoodsList(true);
};

// 搜索商品
const handleSearch = () => {
  page.value = 1;
  noMore.value = false;
  fetchGoodsList(true);
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  page.value = 1;
  noMore.value = false;
  fetchGoodsList(true);
};

// 加载更多
const loadMore = () => {
  if (noMore.value || isLoading.value) return;
  fetchGoodsList();
};

// 跳转到商品详情
const handleProductClick = (item: any) => {
  uni.navigateTo({
    url: `/pages/mall/detail?id=${item.id}`
  });
};

onMounted(() => {
  fetchTypeList();
});
</script>

<style lang="scss" scoped>
.mall-container {
  min-height: 100vh;
  background: #f8f8f8;
  box-sizing: border-box;
  overflow-x: hidden;
  
  .search-box {
    padding: 20rpx 30rpx;
    background: #fff;
    
    .search-bar {
      position: relative;
      display: flex;
      align-items: center;
      background: #f5f5f5;
      height: 72rpx;
      border-radius: 36rpx;
      padding: 0 30rpx;
      
      .label {
        font-size: 28rpx;
        color: #333;
        margin-right: 20rpx;
      }
      
      input {
        flex: 1;
        height: 100%;
        font-size: 28rpx;
        
        &::placeholder {
          color: #999;
        }
      }
      
      .search-icon {
        position: relative;
        width: 40rpx;
        height: 40rpx;
        margin-top: 10rpx;
      }
    }
  }
  
  .tag-list {
    padding: 20rpx 0;
    background: #fff;
    white-space: nowrap;
    margin-bottom: 20rpx;
    
    .tag-item {
      display: inline-block;
      padding: 12rpx 32rpx;
      margin: 0 16rpx;
      font-size: 28rpx;
      color: #666;
      background: #f5f5f5;
      border-radius: 32rpx;
      
      &.active {
        color: #fff;
        background: #4e6ef2;
      }
      
      &:first-child {
        margin-left: 30rpx;
      }
      
      &:last-child {
        margin-right: 30rpx;
      }
    }
  }
  
  .product-list {
    height: calc(100vh - 220rpx);
    padding: 0 30rpx;
    box-sizing: border-box;
    
    .product-item {
      display: flex;
      padding: 30rpx;
      background: #fff;
      border-radius: 20rpx;
      margin-bottom: 20rpx;
      
      .product-image {
        width: 200rpx;
        height: 200rpx;
        border-radius: 12rpx;
        margin-right: 24rpx;
      }
      
      .product-info {
        flex: 1;
        overflow: hidden;
        
        .product-name {
          font-size: 32rpx;
          color: #333;
          font-weight: 500;
          margin-bottom: 12rpx;
        }
        
        .project-info {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 12rpx;
          
          .label {
            margin-right: 10rpx;
          }
        }
        
        .price-info {
          display: flex;
          align-items: baseline;
          
          .price {
            font-size: 36rpx;
            color: #ff4b33;
            font-weight: bold;
            margin-right: 16rpx;
            
            .symbol {
              font-size: 24rpx;
            }
          }
          
          .original-price {
            font-size: 24rpx;
            color: #999;
            text-decoration: line-through;
          }
        }
      }
    }
  }
  
  .loading, .no-more {
    text-align: center;
    padding: 20rpx;
    font-size: 24rpx;
    color: #999;
  }
}
</style>